import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import NavBarConfig from "../modules/NavBar";
import http from "../../util/http";
import { CURRENCY } from "../../config/Api";
import { toast } from "../../util/tip";
import currencyStyles from "../../style/pages/currencyselection";
import { Color } from "../../style/common";

class CurrencySelection extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerTitle: "幣種選擇"
      },
      navigation
    );

  state = {
    currencies: [],
    isRequesting: false
  };

  componentWillMount() {
    this.getcurrencyList();
  }

  async getcurrencyList() {
    let data = await http.get(CURRENCY);
    this.setState({
      currencies: data.data.currencies
    });
  }

  handleToggleCurrency(currency) {
    this.setState({ currencies: [currency] });
  }

  async handlesetCurrency() {
    if (this.state.isRequesting) return;
    await this.setState({
      isRequesting: true
    });
    const data = await http.put(CURRENCY, {
      currencies: this.state.currencies
    });
    if (data) {
      toast("設置成功");
    }
    this.setState({
      isRequesting: false
    });
  }

  render() {
    return (
      <View>
        <View style={currencyStyles.bgtCoinContain}>
          <View>
            {["USD", "CNY", "BTC", "ETH", "BCH"].map(item => (
              <TouchableOpacity
                key={item}
                style={currencyStyles.coinItem}
                onPress={() => this.handleToggleCurrency(item)}
              >
                <View
                  style={[
                    currencyStyles.coinSpan,
                    {
                      backgroundColor:
                        this.state.currencies.indexOf(item) != -1
                          ? Color
                          : "#f2f2f2"
                    }
                  ]}
                />
                <Text style={currencyStyles.coinText}>{item}</Text>
              </TouchableOpacity>
            ))}
          </View>

          <Text style={currencyStyles.coinTip}>展示在首頁等價幣種</Text>
          <TouchableOpacity onPress={this.handlesetCurrency.bind(this)}>
            <Text style={currencyStyles.coinConfirm}>確 定</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

export default CurrencySelection;
